package com.ruoyi.client.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.client.config.properties.WxMpProperties;
import com.ruoyi.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description 微信小程序 配置
 * @Author huangxiong
 * @Date 2022/8/31 14:03
 * @Version V1.0
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {

    private final WxMpProperties properties;

    @Autowired
    public WxMpConfiguration(WxMpProperties properties) {
        this.properties = properties;
    }

    @Bean
    public WxMaService getWxService() {
        if (properties == null) {
            throw new BaseException("微信小程序配置信息异常！！！！");
        }
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(properties.getAppid());
        config.setSecret(properties.getSecret());
        config.setToken(properties.getToken());
        config.setAesKey(properties.getAesKey());
        config.setMsgDataFormat(properties.getMsgDataFormat());

        WxMaService maServices = new WxMaServiceImpl();
        maServices.setWxMaConfig(config);

        return maServices;
    }

    @Bean
    public WxPayService getPayService() throws WxPayException {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(properties.getAppid());
        payConfig.setMchId(properties.getMchId());
        payConfig.setMchKey(properties.getMchKey());
        payConfig.setPrivateKeyPath("classpath:cert/apiclient_key.pem");
        payConfig.setPrivateCertPath("classpath:cert/apiclient_cert.pem");
        payConfig.setKeyPath("classpath:cert/apiclient_cert.p12");
        payConfig.setNotifyUrl(properties.getNotifyUrl());
        payConfig.setApiV3Key(properties.getMchKey());
        payConfig.setCertSerialNo(properties.getCertSerialNo());


        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        payConfig.getVerifier();
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);

        return wxPayService;
    }


}
